package cn.com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (response instanceof HttpServletResponse&&
                request instanceof HttpServletRequest){
            HttpServletResponse rp=(HttpServletResponse)response;
            HttpServletRequest rq=(HttpServletRequest)request;
            rp.setHeader("Access-Control-Allow-Origin", rq.getHeader("origin"));
            rp.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
            rp.setHeader("Access-Control-Allow-Methods","POST,GET");
            rp.setHeader("Access-Control-Allow-Credentials","true");
            rp.setHeader("Content-Type", "application/json;charset=utf-8");
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
